package com.handydata.antifraud.ws.dap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.common.exception.WsInvokeException;
import com.handydata.antifraud.to.dap.TengxunYunReqTO;
import com.handydata.antifraud.to.dap.TengxunYunResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.ws.WsInvocationService;
import com.handydata.common.util.Md5Utils;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

import java.util.Arrays;
import java.util.Date;

/**
 * 腾讯云反欺诈信息
 *
 */
@Slf4j
@Service("tengxunYunWsService")
@Comment("腾讯反欺诈数据")
public class TengxunYunWsServiceImpl extends DataPlatformWsService<TengxunYunReqTO, TengxunYunResTO> implements
		WsInvocationService<TengxunYunReqTO, TengxunYunResTO> {

	@Override
	public TengxunYunResTO query(TengxunYunReqTO req) throws WsInvokeException {
		log.info("腾讯反欺诈数据请求参数 {}", req);
		TengxunYunResTO resTO = new TengxunYunResTO();
		if (StringUtils.isEmpty(req.getName())) {
			log.error("腾讯反欺诈数据参数校验 {}", "name为空");
			resTO.setResCode("1111");
			resTO.setResMsg("腾讯反欺诈数据接口name参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getIdCard())) {
			log.error("腾讯反欺诈数据参数校验 {}", "idCard为空");
			resTO.setResCode("1111");
			resTO.setResMsg("腾讯反欺诈数据接口idCard参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getPhoneNum())) {
			log.error("腾讯反欺诈数据参数校验 {}", "mobile为空");
			resTO.setResCode("1111");
			resTO.setResMsg("腾讯反欺诈数据接口mobile参数为空");
			return resTO;
		}
		this.dataType = DataSourceCode.TENG_XUN_YUN.getCode();
		resTO = executeQuery(req);
		// 行内压测挡板处理
//		try {
//			Thread.sleep(250);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		resTO.setRiskScoreOfTengxunYun(94);
//		resTO.setResCode("0000");
//		resTO.setResMsg("查询成功");
//		// 挡板入库
//		DataCallLogsReqBO dataCallLogsReqBO = new DataCallLogsReqBO();
//		dataCallLogsReqBO.setId(UUID.randomUUID().toString().replace("-", ""));
//		dataCallLogsReqBO.setParams(JSONObject.toJSONString(req));
//		dataCallLogsReqBO.setElapsed(250);
//		dataCallLogsReqBO.setWselapsed(250);
//		dataCallLogsReqBO.setDataType(this.dataType);
//		dataCallLogsReqBO.setResCode("0000");
//		dataCallLogsReqBO.setResMsg("查询成功");
//		dataCallLogsReqBO.setResult("riskSocre：90");
//		dataCallLogsReqBO.setOrderId(req.getOrderId());
//		dataCallLogsReqBO.setUpdateTime(new Date());
//		dataCallLogsReqBO.setCreateTime(new Date());
//		dataCallLogsService.createDataCallLogs(dataCallLogsReqBO);
		return resTO;
	}

	@Override
	protected String createQueryXml(TengxunYunReqTO req) {
		StringBuilder xml = new StringBuilder();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
		xml.append("<subatm>");
		xml.append("<application>GwBiz.Req</application>");
		xml.append("<version>2.0.0</version>");
		xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
		xml.append("<transCode>300614</transCode>");
		xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
		xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
		xml.append("<cid>").append(Md5Utils.md5ToHexStr(req.getIdCard())).append("</cid>");
//		xml.append("<cid>").append(req.getIdCard()).append("</cid>");
		xml.append("<name>").append(req.getName()).append("</name>");
		xml.append("<mobile>").append(Md5Utils.md5ToHexStr(req.getPhoneNum())).append("</mobile>");
//		xml.append("<mobile>").append(req.getPhoneNum()).append("</mobile>");
		xml.append("</subatm>");
		log.info("腾讯云反欺诈信息调用翰迪数据平台请求报文：{}", xml);
		req.setQueryXml(xml.toString());
		return xml.toString();
	}

	@Override
	protected TengxunYunResTO parseResultAndSave(String resultXml, String orderId, Date createDate) {
		log.info("调用腾讯云反欺诈信息接口返回报文：{}", resultXml);
		TengxunYunResTO resTO = new TengxunYunResTO();
		try {
			//解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if (null != jasonObject) {
				if ("0000".equals(jasonObject.get("resCode"))) {
					JSONObject data = JSONObject.parseObject(jasonObject.getString("data"));
					int riskScore = (Integer)data.get("riskScore");
					JSONArray blackTypeArr = JSONObject.parseArray(data.getString("riskInfo"));
					if (blackTypeArr != null && !blackTypeArr.isEmpty()) {
						int[] riskCode2 = new int[blackTypeArr.size()];
						for ( int i=0; i<blackTypeArr.size(); i++) {
							JSONObject riskCode1 =(JSONObject) blackTypeArr.get(i);
							int num = riskCode1.getInteger("riskCode");
							riskCode2[i] = num;
						}
						int max = Arrays.stream(riskCode2).max().getAsInt();
						resTO.setTxFraudRiskCode(max);
					}
					resTO.setTxFraudRiskScore(riskScore);
					resTO.setRiskScoreOfTengxunYun(riskScore);
				} 
				resTO.setResCode((String)jasonObject.get("resCode"));
				resTO.setResMsg((String)jasonObject.get("resMsg"));
			} else {
				resTO.setResCode("0001");
				resTO.setResMsg("腾讯云反欺诈信息接口返回失败");
			}
		} catch (Exception e) {
			log.info("调用腾讯云反欺诈信息接口返回报文解析异常：{}", e);
			resTO.setResCode("1111");
			resTO.setResMsg("调用腾讯云反欺诈信息接口异常");
		}
		log.info("调用腾讯云反欺诈信息接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}

	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, TengxunYunReqTO.class);
	}

}
